package com.kecheng.util;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class ImgCompose {
	 /**
	      * 
	      * @Title: 构造图片
	      * @Description: 生成水印并返回java.awt.image.BufferedImage
	      * @param file
	      *            源文件(图片)
	      * @param waterFile
	      *            水印文件(图片)
	      * @param x
	      *            距离右下角的X偏移量
	      * @param y
	      *            距离右下角的Y偏移量
	      * @param alpha
	      *            透明度, 选择值从0.0~1.0: 完全透明~完全不透明
	      * @return BufferedImage
	      * @throws IOException
	      */
	     public static void imgCompose(File bjfile, File erweimaFile, File txfile,String nickname,String saveFilePath) throws IOException {
	    	 
	    	 float alpha = 1f;
	    	 // 获取底图
	         BufferedImage buffImg = ImageIO.read(bjfile);
	         int ImgWidth = buffImg.getWidth();// 获取底图的宽度
	         int ImgHeight = buffImg.getHeight();// 获取底图的高度
	         // 获取二维马层图
	         BufferedImage erweimaImg = ImageIO.read(erweimaFile);
	         // 获取头像层图
	         BufferedImage txmg = ImageIO.read(txfile);
	         
	         // 创建Graphics2D对象，用在底图对象上绘图
	         Graphics2D g2d = buffImg.createGraphics();
	         // 在图形和图像中实现混合和透明效果
	         g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
	         // 绘制
	         g2d.drawImage(erweimaImg,(int)(ImgWidth*0.35), (int)(ImgHeight*0.73), (int)(ImgWidth*0.3),(int)(ImgWidth*0.3), null);
	         //
	         g2d.drawImage(txmg,(int)(ImgWidth*0.23), (int)(ImgHeight*0.15), (int)(ImgWidth*0.15),(int)(ImgWidth*0.15), null);
	         
	         g2d.setColor(Color.white);//内容颜色
	         g2d.setFont(new Font(null,Font.PLAIN,24));
	         g2d.drawString(nickname,(int)(ImgWidth*0.4), (int)(ImgHeight*0.18));
	         g2d.drawString("发现了好东西，并分享给你~",(int)(ImgWidth*0.4), (int)(ImgHeight*0.21));
	         g2d.dispose();// 释放图形上下文使用的系统资源
	         
	         int temp = saveFilePath.lastIndexOf(".") + 1;
	         try {
	             ImageIO.write(buffImg, saveFilePath.substring(temp), new File(saveFilePath));
	         } catch (IOException e1) {
	             e1.printStackTrace();
	         }
	     }
	 
	     /**
	      * @param args
	      * @throws IOException
	      *             IO异常直接抛出了
	      * @author bls
	      */
	     public static void main(String[] args) throws IOException {
	    	 //背景图
	         String sourceFilePath = "C:\\images\\2.png";
	         //上层图片
	         String waterFilePath = "C:\\images\\5.png";
	         //新图片
	         String saveFilePath = "C:\\images\\25.png";
	         
	         imgCompose(new File(sourceFilePath),new File(waterFilePath),new File(waterFilePath),"小赵",saveFilePath);
	     }
	     
	     
}

